package com.lhfeiyu.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Assets;
import com.lhfeiyu.config.Tip;
import com.lhfeiyu.config.base.BaseAssets;
import com.lhfeiyu.config.base.BaseConst;
import com.lhfeiyu.config.base.BaseTip;
import com.lhfeiyu.dao.AuctionMicroMapper;
import com.lhfeiyu.dao.AuctionMicroOffersMapper;
import com.lhfeiyu.dao.base.BaseDictMapper;
import com.lhfeiyu.dao.base.BaseGoodsMapper;
import com.lhfeiyu.dao.base.BaseNoticeMapper;
import com.lhfeiyu.dao.base.BaseOrderGoodsMapper;
import com.lhfeiyu.dao.base.BaseOrderInfoMapper;
import com.lhfeiyu.dao.base.BaseUserAddressMapper;
import com.lhfeiyu.dao.base.BaseUserMapper;
import com.lhfeiyu.dao.base.BaseUserPraiseMapper;
import com.lhfeiyu.po.AuctionMicro;
import com.lhfeiyu.po.AuctionMicroOffers;
import com.lhfeiyu.po.base.BaseGoods;
import com.lhfeiyu.po.base.BaseNotice;
import com.lhfeiyu.po.base.BaseOrderGoods;
import com.lhfeiyu.po.base.BaseOrderInfo;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.po.base.BaseUserAddress;
import com.lhfeiyu.po.base.BaseUserFund;
import com.lhfeiyu.po.base.BaseUserPraise;
import com.lhfeiyu.service.base.BaseCommonFundService;
import com.lhfeiyu.service.base.CommonService;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.DateFormat;
import com.lhfeiyu.tools.base.Result;
import com.lhfeiyu.tools.base.WxMessageFactory;

/**
 * <strong> 描&nbsp;&nbsp;&nbsp;&nbsp;述：</strong> 业务层：AuctionMicro <p>
 * <strong> 作&nbsp;&nbsp;&nbsp;&nbsp;者：</strong> 虞荣华  <p>
 * <strong> 编写时间：</strong>2016年3月20日22:22:22<p>
 * <strong> 公&nbsp;&nbsp;&nbsp;&nbsp;司：</strong> 成都蓝海飞鱼科技有限公司 http://lhfeiyu.com <p>
 * <strong> 版&nbsp;&nbsp;&nbsp;&nbsp;本：</strong> 2.0 <p>
 * <strong> 备&nbsp;&nbsp;&nbsp;&nbsp;注：</strong> 业务：拍卖-微拍表 <p>
 */
@Service
public class AuctionMicroService extends CommonService<AuctionMicro> {

	@Autowired
	AuctionMicroMapper auctionMicroMapper;
	@Autowired
	AuctionMicroOffersMapper amoMapper;
	@Autowired
	BaseUserAddressMapper uaMapper;
	@Autowired
	BaseOrderInfoMapper orderInfoMapper;
	@Autowired
	BaseOrderGoodsMapper orderGoodsMapper;
	@Autowired
	BaseGoodsMapper goodsMapper;
	@Autowired
	BaseNoticeMapper noticeMapper;
	@Autowired
	BaseDictMapper dictMapper;
	@Autowired
	BaseUserMapper userMapper;
	@Autowired
	BaseUserPraiseMapper userPraiseMapper;
	@Autowired
	BaseCommonFundService cfService;
	
	/**
	 * 根据查询条件，查询列表数据，组装为json返回  （初始版本为自动生成）
	 * @param json
	 * @param map 查询条件map
	 * @return JSONObject json:{rows:dataList,total:total,status:'success',success:'success'}
	 */ 
	public JSONObject getAuctionMicroListSimple(JSONObject json, Map<String, Object> map) {
		List<AuctionMicro> dataList = auctionMicroMapper.selectListByCondition(map);
		Integer total = auctionMicroMapper.selectCountByCondition(map);
		return Result.gridData(dataList, total, json);
	}
	
	public JSONObject updateGetListAndCreaseVisitNum(JSONObject json, Map<String, Object> map) {
		Integer total = auctionMicroMapper.selectCountByCondition(map);
		List<AuctionMicro> dataList = auctionMicroMapper.selectListByCondition(map);
		String amIds = "";
		map.clear();
		map.put("praiseType", "2");
		map.put("start", 0);
		map.put("count", 10);
		for(AuctionMicro am : dataList){
			int amId = am.getId();
			map.put("praiseId", amId);//点赞
			List<BaseUserPraise> userPraiseList = userPraiseMapper.selectListByCondition(map);
			Integer count = userPraiseMapper.selectCountByCondition(map);
			am.setUserPraiseCount(count);
			am.setUserPraiseList(userPraiseList);
			amIds += "," + amId;
		}
		if(amIds.length()>0){
			amIds = amIds.substring(1);
			map.clear();
			map.put("expression1", "visit_num=visit_num+1");//累张访问数量
			map.put("ids", amIds);
			auctionMicroMapper.updateFieldByIds(map);
		}
		return Result.gridData(dataList, total, json);
	}
	
	/**
	 * 新增或修改 - AuctionMicro  （初始版本为自动生成）
	 * @param json 消息数据容器对象（主要用于保存提示消息或数据）
	 * @param auctionMicro AuctionMicro对象
	 * @param updatedBy 操作人名称（数据库记录）
	 * @return JSONObject
	 */
	public JSONObject addOrUpdateAuctionMicroSimple(JSONObject json, AuctionMicro obj, String updatedBy){
		//判断不能为空的字段，或验证其他必须条件
		//String content = obj.getContent();
		//if(!Check.isNotNull(content)){
		//	return Result.failure(json, "内容不能为空", "content_null");
		//}
		if(null == obj.getId()){//添加
			return addAuctionMicroSimple(json, obj, updatedBy);
		}else{//修改
			return updateAuctionMicroSimple(json, obj, updatedBy);
		}
	}
	
	/**
	 * 新增  - AuctionMicro（代码若已经存在则提示失败）  （初始版本为自动生成）
	 * @param json 消息数据容器对象（主要用于保存提示消息或数据）
	 * @param auctionMicro AuctionMicro对象
	 * @param updatedBy 操作人名称（数据库记录）
	 * @return JSONObject
	 */
	public JSONObject addAuctionMicroSimple(JSONObject json, AuctionMicro obj, String updatedBy){
		//判断不能重复的字段，或验证其他必须条件
		Date date = new Date();
		obj.setId(null);
		obj.setSerial(CommonGenerator.getSerialByDate(Assets.serial_prefix_auctionMicro));
		obj.setMainStatus(1);
		obj.setCreatedBy(updatedBy);
		obj.setCreatedAt(date);
		auctionMicroMapper.insert(obj);
		json.put("id", obj.getId());
		return Result.success(json);
	}
	
	/**
	 * 修改 - AuctionMicro（ID不能为空，数据库中必须存在该ID的数据）  （初始版本为自动生成）
	 * @param json 消息数据容器对象（主要用于保存提示消息或数据）
	 * @param auctionMicro AuctionMicro对象
	 * @param updatedBy 操作人名称（数据库记录）
	 * @return JSONObject
	 */
	public JSONObject updateAuctionMicroSimple(JSONObject json, AuctionMicro obj, String updatedBy){
		Date date = new Date();
		Integer objId = obj.getId();
		if(null == objId){//添加
			return Result.failure(json, "编号为空，无法进行执行修改", "auctionMicroId_null");
		}
		AuctionMicro dbAuctionMicro = auctionMicroMapper.selectByPrimaryKey(objId);
		if(null == dbAuctionMicro){
			return Result.failure(json, "该条数据不存在，无法进行执行修改", "auctionMicro_null");
		}
		obj.setUpdatedBy(updatedBy);
		obj.setUpdatedAt(date);
		auctionMicroMapper.updateByPrimaryKeySelective(obj);
		return Result.success(json);
	}

	public List<AuctionMicro> updateGetAuctionMicroList(Map<String, Object> map){
		//List<AuctionMicro> newMicroList = new ArrayList<AuctionMicro>();
		/*Object pageObj = map.get("page");
		Integer page = 1;
		if(null != pageObj){
			page = Integer.valueOf((String)pageObj);
		}
		if(page == 1){	//查询指定的微拍，放在第一位
			Object auctionIdObj = map.get("auctionId");
			if(null != auctionIdObj){//查询需要放在最前面的拍卖
				Integer auctionId = Integer.valueOf((String)auctionIdObj);
				Map<String, Object> theMap = CommonGenerator.getHashMap();
				theMap.put("auctionId", auctionId);
				AuctionMicro db_AuctionMicro = auctionMicroMapper.selectByCondition(map);
				if(null != db_AuctionMicro){
					newMicroList.add(db_AuctionMicro);
					map.remove("auctionId");
					map.put("notAuctionId", auctionId);
				}
			}
		}else{//如果已经不是在第一页，去掉指定微拍ID
			//map.remove("auctionId");
			//map.remove("auctionSerial");
		}*/
		
		//map.put("orderBy", "id");//避免冲突
		//map.put("ascOrdesc", "desc");
		List<AuctionMicro> auctionMicroList = auctionMicroMapper.selectListByCondition(map);
		
		String amIds = "";
		for(AuctionMicro am :auctionMicroList){
			Integer auctionId = am.getId();
			amIds += "," + auctionId;
			map.put("auctionId", auctionId);
			map.put("orderBy", "id");
			map.put("ascOrdesc", "desc");//最近出价排在最前面
			map.put("start", 0);
			map.put("count", 5);
			List<AuctionMicroOffers> amoList = amoMapper.selectListByCondition(map);//微拍出价
			if(Check.isNotNull(amoList)){
				am.setAmoList(amoList);
			}
			map.clear();
			map.put("praiseType", 2);//点赞类型ID（1：点赞专场，2：点赞微拍，3：点赞即时拍）
			map.put("praiseId", auctionId);
			map.put("count", 10);
			map.put("start", 0);
			List<BaseUserPraise> userPraiseList = userPraiseMapper.selectListByCondition(map);
			if( Check.isNotNull(userPraiseList) ){
				am.setUserPraiseList(userPraiseList);
				Integer count = userPraiseMapper.selectCountByCondition(map);
				am.setUserPraiseCount(count);
			}
			//newMicroList.add(am);
		}
		
		if(amIds.length()>0){
			amIds = amIds.substring(1);
			map.clear();
			map.put("expression1", "visit_num=visit_num+1");//累张访问数量
			map.put("ids", amIds);
			auctionMicroMapper.updateFieldByIds(map);
		}
		
		return auctionMicroList;
	}
	
	/**
	 * 检查所有微拍是否结束
	 * @param json
	 * @return
	 */
	public JSONObject updateCheckAuctionMicroOver(JSONObject json){
		if(null == json)json = new JSONObject();
		Date date = new Date();
		Map<String,Object> map = CommonGenerator.getHashMap();
		map.put("mainStatusNull", 1);
		List<AuctionMicro> amList = auctionMicroMapper.selectListByCondition(map);
		if(!Check.isNotNull(amList)){
			return json;
		}
		Date now = new Date();
		for(AuctionMicro am : amList){
			if(Check.isNotNull(am.getOrderSn()))continue;//已经生成订单，则不做处理
			Integer goodsId = am.getGoodsId();
			if(Check.isNull(goodsId))continue;
			Date endTime = am.getEndTime();
			if(null != endTime && endTime.after(now)){//如果结束时间为空或在当前时间之后，则还不应该设置为结束
				Date endTimeBefor = new Date(endTime.getTime() - (10* 60*1000));
				if(now.before(endTime) && now.after(endTimeBefor)){//如果结束时间为空或在当前时间之后，则还不应该设置为结束
					//System.out.println("*******************");	
					//发送拍卖结束提醒
					if(!am.getRemark().equals("noticesed")){
						BaseUser user = userMapper.selectByPrimaryKey(am.getUserId());
						WxMessageFactory.auctionMicroOver(user.getWxOpenid(), "感谢您参与拍卖，本次拍卖10分钟后结束！",am.getAuctionSerial(), am.getGoodsName(), "本场拍卖结束时间："+endTime);
					}
				map.clear();
//				map.put("auctionId", am.getId());
				List<AuctionMicroOffers> amoList = amoMapper.selectListByNotCf(am.getId());
					for(AuctionMicroOffers amo : amoList){
						String openId = amo.getOpenId();
						Date endDate = am.getEndTime();
						BaseUser users = userMapper.selectByPrimaryKey(amo.getOfferUserId());
						Date endDateBefor = new Date(endDate.getTime() - (10* 60*1000));
						String timeStr = "";
						if(null != endDate && endDateBefor.after(date)){
							String end = DateFormat.daySdf.format(endDate);
							//System.out.println("结束时间2:"+endDateBefor);
							timeStr = "本场拍卖结束时间："+end;
						}
						// _@微信消息通知WxNotice@_
						if(!am.getRemark().equals("noticesed")){
							WxMessageFactory.auctionMicroOver(users.getWxOpenid(), "感谢您参与拍卖，本次拍卖10分钟后结束！",am.getAuctionSerial(), am.getGoodsName(), timeStr);
						}
					}
					
						
				}
				am.setRemark("noticesed");
				auctionMicroMapper.updateByPrimaryKeySelective(am);
				continue;
			}
			
			Integer auctionId = am.getId();
			Integer offerUserId = am.getOfferUserId();
			AuctionMicro newAm = new AuctionMicro();
			newAm.setId(auctionId);
			if(null != offerUserId){
				newAm.setMainStatus(3);//有人出价 - 生成订单
				//Goods db_goods = goodsMapper.selectByPrimaryKey(goodsId);
				/*//计算推广费，暂时隐藏//TODO 检查推广收益
				Integer bounsType = db_goods.getBonusTypeId();
				BigDecimal bouns = db_goods.getBonus();
				BigDecimal shopPrice = db_goods.getShopPrice();
				BigDecimal promoteBenifitMoney = null;
				if(null != bounsType){//判读是否有推广
					if(bounsType == 1){//按金额算推广费
						promoteBenifitMoney = bouns;
					}
					if(bounsType == 2){//按百分比算推广费
						BigDecimal shareFee = bouns.divide(new BigDecimal(100));
						promoteBenifitMoney = shareFee.multiply(shopPrice);
					}
					if(null != promoteBenifitMoney){
						promoteBenifitMoney = promoteBenifitMoney.setScale(2, BigDecimal.ROUND_HALF_UP);//设置保留两位小数
					}
				}*/
				BaseGoods goods = new BaseGoods();
				goods.setId(goodsId);
				goods.setGoodsSn(am.getGoodsSn());
				goods.setGoodsName(am.getGoodsName());
				BaseUser userss = userMapper.selectByPrimaryKey(am.getOfferUserId());
				addOrderInfo(json, offerUserId, goods, am.getOfferPrice(), auctionId, userss.getWxOpenid(), am.getPromoteUserSerial(), null);
			}else{//TODO 如果没有人出价就把产品改为普通状态
				map.clear();
				newAm.setMainStatus(4);//没人出价
				map.put("mainStatus", 1);//普通状态
				map.put("updatedAt", date);
				map.put("updatedBy", BaseConst.operater_system);
				map.put("goodsIds", goodsId);
				goodsMapper.updateStatusByIds(map);
			}
			auctionMicroMapper.updateByPrimaryKeySelective(newAm);
		}
		return Result.success(json);
	}
	
	public JSONObject finishAuctionMicro(JSONObject json, Integer amId){
		
		AuctionMicro am = auctionMicroMapper.selectByPrimaryKey(amId);
		Integer goodsId = am.getGoodsId();
		Integer offerUserId = am.getOfferUserId();
				
		AuctionMicro new_am = new AuctionMicro();
		new_am.setId(amId);
		new_am.setMainStatus(2);//没有出价
		
		if(null != offerUserId){
			new_am.setMainStatus(3);//有人出价
			//TODO 生成订单
			/*Goods db_goods = goodsMapper.selectByPrimaryKey(goodsId);
			Integer bounsType = db_goods.getBonusTypeId();
			BigDecimal bouns = db_goods.getBonus();
			BigDecimal shopPrice = db_goods.getShopPrice();
			BigDecimal promoteBenifitMoney = null;
			if(null != bounsType){//判读是否有推广
				if(bounsType == 1){//按金额算推广费
					promoteBenifitMoney = bouns;
				}
				if(bounsType == 2){//按百分比算推广费
					BigDecimal shareFee = bouns.divide(new BigDecimal(100));
					promoteBenifitMoney = shareFee.multiply(shopPrice);
				}
			}*/
			BaseGoods goods = new BaseGoods();
			goods.setId(goodsId);
			goods.setGoodsSn(am.getGoodsSn());
			goods.setGoodsName(am.getGoodsName());
			goods.setMainStatus(78);//冻结中
			goodsMapper.updateByPrimaryKey(goods);
			addOrderInfo(json, offerUserId, goods, am.getOfferPrice(), goodsId, am.getUserOpenId(), null, null);
			if(!Result.hasError(json)){
				json.put("jumpToPayAuctionMicroOrder", 1);
			}
			
			
			// TODO TODO TODO TODO TODO TODO:需要完善
			
			
		}
		auctionMicroMapper.updateByPrimaryKeySelective(new_am);
		return Result.success(json);
	}
	
	public JSONObject addOrderInfo(JSONObject json, Integer userId, BaseGoods goods, BigDecimal shopPrice, Integer auctionId, String openId,String promoteUserSerial,BigDecimal promoteBenifitMoney){
		if(null == shopPrice || shopPrice.doubleValue() <= 0 || shopPrice.doubleValue() >= 10000000){
			return Result.failure(json, BaseTip.msg_price_wrong, BaseTip.code_price_wrong);
		}
		if(null == goods || null == goods.getId()){
			return Result.failure(json, BaseTip.msg_goods_null, BaseTip.code_goods_null);
		}
		shopPrice = shopPrice.setScale(2, BigDecimal.ROUND_HALF_UP);//设置保留两位小数
		//新增订单
		BaseUser user = userMapper.selectByPrimaryKey(userId);
		//Integer userId = user.getId();
		Map<String, Object> map = CommonGenerator.getHashMap();
		map.put("userId", userId);
		map.put("isDefault", 2);//常用收货地址
		BaseUserAddress address = uaMapper.selectByCondition(map);
		Date date = new Date();
		BaseOrderInfo order = new BaseOrderInfo();
		if(null != address){//暂时这里不验证收货地址，付款时再验证
			//return Result.failure(json, BaseTip.msg_address_null, BaseTip.code_address_null);
			order.setUsername(address.getReceiverName());
			order.setProvince(address.getProvinceName());
			order.setCity(address.getCityName());
			order.setAddress(address.getAddressDetail());
			order.setPhone(address.getPhone());
		}
		order.setEmail(user.getEmail());
		order.setOrderSn(CommonGenerator.getSerialByDate(BaseAssets.serial_prefix_orderInfo));
		order.setUserId(userId);
		order.setOrderStatusCode(BaseConst.order_status_todo);		// 数据字典代码-订单状态：未完成
		order.setShippingStatusCode(BaseConst.shipping_status_todo);// 数据字典代码-商品配送情况：未发货
		order.setPayStatusCode(BaseConst.pay_status_todo);			// 数据字典代码-支付状态：未付款
		order.setOrderDoneStausCode(BaseConst.order_done_status_no);// 数据字典代码-订单完成状态：未完成
		order.setMainStatus(1);// 状态（1未结束订单，2已结束订单，3无效订单）
		order.setCreatedAt(date);
		order.setCreatedBy(BaseConst.operater_system);
		orderInfoMapper.insert(order);//新增订单
		Integer orderId = order.getId();
		
		BaseOrderGoods og = new BaseOrderGoods();//新增orderGoods
		og.setOrderId(orderId);
		og.setGoodsId(goods.getId());
		og.setGoodsName(goods.getGoodsName());
		og.setGoodsSn(goods.getGoodsSn());
		og.setGoodsType(1);//商品类型（1普通商品，2批发城商品）
		og.setGoodsFrom(4);//商品来源（1批发城，2店铺，3专场，4微拍，5即时拍）
		og.setGoodsNumber(1);
		//og.setPromoteUsername(promoteUserSerial);//推广人编号-后期开发
		//og.setPromoteBenifitMoney(promoteBenifitMoney);//推广金额-后期开发
		og.setShopPrice(shopPrice);
		og.setMainStatus(1);
		og.setCreatedAt(date);
		og.setCreatedBy(BaseConst.operater_system);
		orderGoodsMapper.insertSelective(og);
		
		BaseGoods newGoods = new BaseGoods();//更新goods状态
		newGoods.setId(goods.getId());
		newGoods.setMainStatus(78);//dict78:冻结中
		newGoods.setUpdatedAt(date);
		newGoods.setUpdatedBy(BaseConst.operater_system);
		goodsMapper.updateByPrimaryKeySelective(newGoods);
		
		//withholdFee();//扣手续费 - 商品确认收货后再收取手续费
		
		String title = "微拍竞拍成功通知";
		String content = Tip.tp_auctionMicro_success;
		if(Check.isNull(goods.getGoodsName()))goods.setGoodsName("");
		content.replace("-GOODS_NAME-", goods.getGoodsName());
		content.replace("-PRICE-", shopPrice.toString());
		map.clear();
		map.put("auctionId", auctionId);
		//TODO 修改
		//auctionMicroMapper.updateOrderSn(map);
		
		BaseNotice notice = new BaseNotice();
		notice.setSerial(CommonGenerator.getSerialByDate("n"));
		notice.setReceiverId(userId);
		notice.setContent(content);
		notice.setReadStatus(1);//未阅读
		notice.setTypeId(20);//竞拍成功通知
		notice.setTitle(title);
		notice.setCreatedAt(date);
		notice.setCreatedBy("-SYS-");
		noticeMapper.insert(notice);//新增通知
		
		//System.out.println("###############################");
		
		// _@微信消息通知WxNotice@_
		WxMessageFactory.bidSuccess(openId, goods.getGoodsName(), String.valueOf(shopPrice));
		return Result.success(json);
	}
	
	public JSONObject addUpdateAuctionMicro(JSONObject json, BaseUser user, AuctionMicro am){
		Date date = new Date();
		/*Calendar c = Calendar.getInstance();
		if(Check.isNotNull(day)){
			c.add(Calendar.DATE, day);
		}else{
			c.add(Calendar.DATE, 15);
		}
		Date endTime = c.getTime();*/
		Integer userId = user.getId();
		String username = user.getUsername();
		Integer goodsId = am.getGoodsId();
		
		if(null == goodsId){
			return Result.failure(json, BaseTip.msg_goods_null, BaseTip.code_goods_null);//商品为空
		}
		BaseGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
		if(null == goods){
			return Result.failure(json, BaseTip.msg_goods_null, BaseTip.code_goods_null);//商品为空
		}
		Integer goodsUserId = goods.getUserId();//商品关联店铺ID
		if( Check.integerNotEqual(userId, goodsUserId) ){
			return Result.failure(json, BaseTip.msg_auth_lack, BaseTip.code_auth_lack);//检查权限
		}
		
		BigDecimal priceBegin = am.getPriceBegin();
		BigDecimal increaseRangePrice = am.getIncreaseRangePrice();
		BigDecimal postageFee = am.getPostageFee();
		BigDecimal bail = am.getBail();
		
		if(null != priceBegin && ( priceBegin.doubleValue() < 0 || priceBegin.doubleValue() >= 100000 )){
			return Result.failure(json, "起拍价只能在0至10万元之间", "priceBegin_invalid");
		}
		if(null != increaseRangePrice && ( increaseRangePrice.doubleValue() < 1 || increaseRangePrice.doubleValue() >= 10000 )){
			return Result.failure(json, "加载幅度只能在1至1万元之间", "increaseRangePrice_invalid");
		}
		if(null != postageFee && ( postageFee.doubleValue() < 0 || postageFee.doubleValue() >= 10000 )){
			return Result.failure(json, "邮费只能在0至1万元之间", "postageFee_invalid");
		}
		if(null != bail && ( bail.doubleValue() < 0 || bail.doubleValue() >= 100000 )){
			return Result.failure(json, "保证金只能在0至10万元之间", "bail_invalid");
		}
		
		//TODO 验证前台输入的各类价格是否合法 - 检查保证金
		//相同代码：AuctionMicroAction-addAuctionMicroOffer，AuctionMicroService-addUpdateAuctionMicro
		//AuctionProfessionAction-addOrUpdateAuctionProfession
		BigDecimal bailBD = am.getBail();
		if(null != bailBD && bailBD.doubleValue() > 0){
			BaseUserFund uf = cfService.selectUserFundByUserId(userId);
			BigDecimal creditMoney = uf.getOtherFund();
			//Integer creditMoney = shop.getCreditMargin();
			if(null == creditMoney || creditMoney.doubleValue() <= 0){//诚信保证金为空
				json.put("moneyLack", bailBD.doubleValue());
				json.put("bail", bailBD.doubleValue());
				return Result.failure(json, BaseTip.msg_creditMoney_null, BaseTip.code_creditMoney_null);
			}else if(creditMoney.doubleValue() < bailBD.doubleValue()){//诚信保证金不足
				String tip = BaseTip.msg_creditMoney_lack.replace("@money@", creditMoney.toString());
				Double moneyLack = bailBD.doubleValue() - creditMoney.doubleValue();
				json.put("moneyLack", moneyLack);
				json.put("bail", bailBD.doubleValue());
				json.put("creditMoney", creditMoney.doubleValue());
				return Result.failure(json, tip, BaseTip.code_creditMoney_lack);
			}
		}
		
		//更新商品信息
		BaseGoods newGoods = new BaseGoods();
		newGoods.setId(goodsId);
		newGoods.setIsSevenReturn(am.getIsSevenReturn());
		newGoods.setPostageFee(am.getPostageFee());
		goodsMapper.updateByPrimaryKeySelective(newGoods);
		
		/*String statusCode = goods.getStatusCode();//不检查商品状态
		if(!Check.strEqual(statusCode, BaseConst.goods_status_sell)){
			return Result.failure(json, BaseTip.msg_goods_status_wrong, BaseTip.code_goods_status_wrong);//商品状态
		}	*/
		/*Integer remainNum = goods.getRemainNumber();//库存数量//不检查库存数量
		if(null == remainNum || remainNum <= 0){
			return Result.failure(json, BaseTip.msg_remainNumber_lack, BaseTip.code_remainNumber_lack);
		}*/
		Integer amId = am.getId();//拍卖ID，存在即修改，不存在即新增
		if(null != amId){
			AuctionMicro dbAm = auctionMicroMapper.selectByPrimaryKey(amId);
			if(null == dbAm){
				Result.failure(json, Tip.msg_auction_null, Tip.code_auction_null);//拍卖为空
			}
			if(Check.integerEqual(2, dbAm.getMainStatus())){
				Result.failure(json, Tip.msg_auction_over, Tip.code_auction_over);//拍卖已经结束
			}
			auctionMicroMapper.updateByPrimaryKeySelective(am);//修改拍卖
		}else{
			AuctionMicro newAM = new AuctionMicro();
			newAM.setUserId(userId);
			newAM.setGoodsId(goodsId);
			newAM.setGoodsName(goods.getGoodsName());
			newAM.setGoodsSerial(goods.getSerial());
			newAM.setGoodsSn(goods.getGoodsSn());
			newAM.setGoodsDescription(goods.getGoodsDescription());
			newAM.setShopId(user.getShopId());
			newAM.setStartTime(date);
			newAM.setEndTime(am.getEndTime());//截止日期
			newAM.setBail(am.getBail());
			newAM.setBuyoutPrice(am.getBuyoutPrice());
			newAM.setIncreaseRangePrice(am.getIncreaseRangePrice());
			newAM.setPriceBegin(am.getPriceBegin());
			newAM.setJoinNum(0);
			newAM.setVisitNum(0);
			newAM.setMainStatus(1);//1未结束，2已结束
			String serial = CommonGenerator.getSerialByDate(Assets.serial_prefix_auctionMicro);
			newAM.setAuctionSerial(serial);
			newAM.setSerial(serial);
			newAM.setCreatedAt(date);
			newAM.setCreatedBy(username);
			auctionMicroMapper.insertSelective(newAM);//新增拍卖
			json.put("amId", newAM.getId());
		}
		//TODO 是否需要修改商品状态（库存为1呢？）
		return Result.success(json);
	}
	
	public JSONObject deleteAuctionMicro(JSONObject json, BaseUser user, Integer amId) throws Exception{
		AuctionMicro dbAm = auctionMicroMapper.selectByPrimaryKey(amId);
		if(null == dbAm){
			Result.failure(json, Tip.msg_auction_null, Tip.code_auction_null);//拍卖为空
		}
		Integer goodsId = dbAm.getGoodsId();
		if(null == goodsId){
			return Result.failure(json, BaseTip.msg_goods_null, BaseTip.code_goods_null);//商品为空
		}
		BaseGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
		if(null == goods){
			return Result.failure(json, BaseTip.msg_goods_null, BaseTip.code_goods_null);//商品为空
		}
		Integer userShopId = user.getShopId();//用户关联的店铺ID
		Integer goodsShopId = goods.getShopId();//商品关联店铺ID
		if( Check.integerNotEqual(goodsShopId, userShopId) ){
			return Result.failure(json, BaseTip.msg_auth_lack, BaseTip.code_auth_lack);//检查权限
		}
		if(Check.integerNotEqual(2, dbAm.getMainStatus()) && null != dbAm.getOfferUserId()){//该次拍卖尚未结束并且已经有买家出价，无法执行删除
			Result.failure(json, Tip.msg_auction_delete_not_over_offered, Tip.code_auction_delete_not_over_offered);
		}
		auctionMicroMapper.deleteByPrimaryKey(amId);
		return Result.success(json);
	}
	
	public JSONObject addBatchAuctionMicroGoods(JSONObject json, BaseUser user, String auctionMicroAry) {
		List<AuctionMicro> amList = JSONObject.parseArray(auctionMicroAry, AuctionMicro.class);
		if(Check.isNull(amList)){
			return Result.failure(json, BaseTip.msg_goods_null, BaseTip.code_goods_null);//商品为空
		}
		for(AuctionMicro am : amList){
			if(Result.hasError(json))return json;
			addUpdateAuctionMicro(json, user, am);
		}
		return Result.success(json);
	}
	
	/**
	 * 逻辑删除 - AuctionMicro  （初始版本为自动生成）
	 * @param json
	 * @param ids ID串
	 * @param updatedBy 操作人名称（数据库记录）
	 * @return JSONObject
	 */
	public JSONObject updateAuctionMicroDeleteSimple(JSONObject json, String ids, String updatedBy) {
		auctionMicroMapper.updateDeletedNowByIds(ids, updatedBy);
		return Result.success(json);
	}
	
	/**
	 * 物理删除 - AuctionMicro  （初始版本为自动生成）
	 * @param json
	 * @param ids ID串
	 * @return JSONObject
	 */
	public JSONObject deleteAuctionMicroThoroughSimple(JSONObject json, String ids) {
		auctionMicroMapper.deleteByIds(ids);
		return Result.success(json);
	}
	
	/**
	 * 恢复 - AuctionMicro（去除逻辑删除状态）  （初始版本为自动生成）
	 * @param json
	 * @param ids ID串
	 * @param updatedBy 操作人名称（数据库记录）
	 * @return JSONObject
	 */
	public JSONObject updateAuctionMicroRecoverSimple(JSONObject json, String ids, String updatedBy) {
		auctionMicroMapper.updateDeletedNullByIds(ids, updatedBy);
		return Result.success(json);
	}
	
	public JSONObject doDelete(JSONObject json, BaseUser user, String serial){
		if(Check.isNull(serial)){
			return Result.failure(json, "拍卖场次编号不能为空", "amSerial_null");
		}
		Map<String, Object> map = CommonGenerator.getHashMap();
		map.put("serial", serial);
		AuctionMicro am = auctionMicroMapper.selectByCondition(map);
		Integer userId = user.getId();
		Integer hostId = am.getUserId();
		if(Check.integerNotEqual(userId, hostId)){
			return Result.failure(json, "权限不足", "auth_lack");
		}
		Integer amId = am.getId();
		if(am.getMainStatus() == 1 && null != am.getOfferUserId()){//正在拍卖中，同时已经有人出价
			return Result.failure(json, "本场拍卖正在拍卖中,并且已经有客户出价，无法删除", "am_ing");
		}else if(am.getMainStatus() == 1 && null == am.getOfferUserId()){//正在拍卖中无人出价，直接删除
			auctionMicroMapper.deleteByPrimaryKey(amId);//未开始或未提交的拍卖可直接删除
			return Result.success(json);
		}else{//已经拍卖结束的拍卖进行逻辑删除
			auctionMicroMapper.updateDeletedNowById(amId, user.getUsername());
			return Result.success(json);
		}
	}

	public List<AuctionMicro> selectListByOfferUserId(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return auctionMicroMapper.selectListByOfferUserId(map);
	}
}